// 对axios进行二次封装
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import _ from 'lodash'
import router from '@/router'
// 初始化loading变量
let loading
// 当前正在请求的数量
let needLoadingRequestCount = 0
// 显示loading
function showLoading(target) {
  // 获取main-wrap的加载框口
  const $homeMain = document.querySelector('.main-wrap')
  if (needLoadingRequestCount === 0 && !loading) {
      loading = Loading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0.5)',
          target: target || $homeMain || 'body'
      })
  }
  needLoadingRequestCount++
}
const service = axios.create({
  baseURL: window.env.BASE_API,
  timeout: 99999999, // 代表请求超时的时间30s
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'tenant': 1
  },
  transformRequest: [function(data) {
    // 如果文件是FormData格式不进行转换
    if(Object.prototype.toString.call(data) === '[object FormData]') return data
    return JSON.stringify(data)
  }]
})

function hideLoading() {
  needLoadingRequestCount--
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) // 做个保护
  if (needLoadingRequestCount === 0) {
  // 关闭loading
      toHideLoading()
  }
}
// 防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
var toHideLoading = _.debounce(() => {
  loading && (loading.close())
  loading = null
}, 300)
service.interceptors.request.use(
  (config)=> {
    // 展示loading
    showLoading(config.headers.loadingTarget)
     // get请求使用params传参
     if (/get/i.test(config.method) || /delete/i.test(config.method)) {
    // eslint-disable-next-line require-atomic-updates
        config.params = config.data
     }
    // 请求头添加token
    let token = ''
    token = localStorage.getItem('TOKEN') || ''
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    if (token) {
        // eslint-disable-next-line require-atomic-updates
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    // 关闭loading
    hideLoading()
    Message({
        message: '服务器请求失败，请稍后再试或联系管理员',
        type: 'error',
        duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  (response) => {
    // 关闭loading
    hideLoading()
    if (response.status === 200) {
        // const res = {
        //   result: response.data,
        //   code: 200
        // }
        const res = response.data
        return res
    }
  },
  error=> {
    // 关闭loading
    console.log(error);
    if(error.response && error.response && error.response.data && error.response.data.message) {
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 3 * 1000
      })
    } else {
      Message({
        message: '系统异常',
        type: 'error',
        duration: 3 * 1000
      })
    }
    hideLoading()
    const href = location.href
    if (href.indexOf('basicInfo') !== -1 || href.indexOf('infoUpdate') !== -1) {
      return Promise.reject(error)
    }
    switch (error.response.status) {
      case 400:
        if (error.response.data.code === 'auth.token.sign.invalid') router.push({ name: 'Login' })
  
        break
      case 401:
        localStorage.removeItem('TOKEN')
        router.push({ name: 'Login' })
  
        break
        // 403 跳转至登录页面（供应商被冻结）
      case 403:
        router.push({ name: 'Login' })
  
        break
        // 404 跳转至404页面
      case 404:
        break
        // 406 跳转至登录页面（个人账号被冻结）
      case 406:
        break
        // 入驻成功
      case 409:
        break
        // token无效
      case 451:
        router.push({ name: 'Login' })
  
        break
        // 500 跳转至维修中页面
      case 500:
        break
      default:
        return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)

export default service
